package org.itboys.admin.service.lasted;


import org.apache.commons.collections.map.HashedMap;
import org.itboys.admin.entity.lasted.SystemMenu;
import org.itboys.admin.entity.lasted.SystemRolePermission;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 作者：jiangxiong
 * 日期：2017年2月27日
 * 联系方式 ：empty90911@126.com
 * 描述：系统_角色和权限关联_Service，江雄重新写的
 */
@Service
public class SystemRolePermissionService extends BaseMongoService<SystemRolePermission> {

  @Autowired
  private SystemMenuService menuService;

    @Resource(name = "adminDS")
    private MongoDataSource ds;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return ds;
    }

    @Override
    protected Class<SystemRolePermission> getEntityClass() {
        return SystemRolePermission.class;
    }



    /**
     * 获取分配菜单数据
     * @param roleId
     * @return
     */
    public List<Map<String,Object>> allotRolePerMenu(Long roleId){
        List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
        Map<String,Object> param = new HashMap<String,Object>();
        //所有菜单
        param.put("isDeleted",0);
        param.put("sort","sequence");
        param.put("order","ASC");

        List<SystemMenu> menus = menuService.list(param);
     //   logger.info("AAAAAAAAAAAAAAA"+ menus.size());

        param.clear();
        param.put("roleId",roleId);
        param.put("type",SystemRolePermission.system_role_permission_type_menu);
        //用户菜单权限
        List<SystemRolePermission> userMenus=super.list(param);

        //组装菜单树，已经勾选已有的菜单权限
        List<SystemMenu> parentMenu = new ArrayList<SystemMenu>();
        List<SystemMenu> childrenMenu = new ArrayList<SystemMenu>();

        for(SystemMenu menu:menus){

            if(LongUtil.isNotNull(menu.getParentId())
            &&menu.getParentId().longValue()==0l){
               // logger.info("父节点");
                parentMenu.add(menu);
            }else{
                //logger.info("子节点");
                childrenMenu.add(menu);
            }
        }
        //logger.info("CCC=="+parentMenu.size());
        //组装TREE
        for(SystemMenu p:parentMenu){
            Map<String,Object> parent = new HashedMap();
            parent.put("id",p.getId());
            parent.put("name",p.getName());
            parent.put("type",SystemRolePermission.system_role_permission_type_menu);
            parent.put("checked",false);
            List< Map<String,Object>> children = new ArrayList< Map<String,Object>>();
            for(SystemMenu c:childrenMenu){
                if(LongUtil.isNotZreo(c.getParentId())&&
                        c.getParentId().longValue()==p.getId()){
                    Map<String,Object> child = new HashedMap();
                    child.put("id",c.getId());
                    child.put("name",c.getName());
                    child.put("type",SystemRolePermission.system_role_permission_type_menu);
                    child.put("checked",false);
                        //匹配子菜单是否勾选
                        for(SystemRolePermission userMenu:userMenus){
                            if(LongUtil.isNotZreo(userMenu.getMenuId())&&
                                    c.getId()==userMenu.getMenuId().longValue()){
                                child.put("checked",true);
                                break;
                            }
                        }

                   children.add(child);
                  // break;
                }
            }
            parent.put("children",children);

            results.add(parent);
        }
        return results;
    }

    /**
     * 获取分配菜单功能数据
     * @param roleId
     */
    public  List<Map<String,Object>> allotRolePerMenuOperate(Long roleId){
        List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
        Map<String,Object> param = new HashMap<String,Object>();
        //所有菜单
        param.put("isDeleted",0);
        param.put("sort","sequence");
        param.put("order","ASC");
        List<SystemMenu> menus = menuService.list(param);
        param.clear();
        param.put("roleId",roleId);
     //   param.put("type",SystemRolePermission.system_role_permission_type_operate);
        //用户功能权限
        List<SystemRolePermission> operatePermissions=new ArrayList<SystemRolePermission>();
        //用户菜单权限
        List<SystemRolePermission> menuPermissions=new ArrayList<SystemRolePermission>();

        for(SystemRolePermission rolePermission:super.list(param)){
            if(rolePermission.getType()==SystemRolePermission.system_role_permission_type_menu){
                menuPermissions.add(rolePermission);
            }
            if(rolePermission.getType()==SystemRolePermission.system_role_permission_type_operate){
                operatePermissions.add(rolePermission);
            }
        }
        logger.info("菜单权限"+menuPermissions.size());
        logger.info("功能权限"+operatePermissions.size());

        //组装菜单树，已经勾选已有的菜单权限
        List<SystemMenu> parentMenu = new ArrayList<SystemMenu>();
        List<SystemMenu> childrenMenu = new ArrayList<SystemMenu>();
        List<SystemMenu> operateMenu = new ArrayList<SystemMenu>();
        for(SystemMenu menu:menus){

            if(LongUtil.isNotNull(menu.getParentId())
                    &&menu.getParentId().longValue()==0l){

                parentMenu.add(menu);
            }else{
                if(menu.getParentId().longValue()==0l){
                    parentMenu.add(menu);
                }else{
                    if(menu.getIsMenu()==1){
                        childrenMenu.add(menu);
                    }else{
                        operateMenu.add(menu);
                    }
                }
            }
        }
        //logger.info("CCC=="+parentMenu.size());
        //组装TREE
        //一级菜单
        for(SystemMenu p:parentMenu){
            Map<String,Object> parent = new HashedMap();
            parent.put("id",p.getId());
            parent.put("name",p.getName());
            parent.put("type",SystemRolePermission.system_role_permission_type_menu);
            parent.put("checked",false);
            List< Map<String,Object>> children = new ArrayList< Map<String,Object>>();
            //二级菜单
            for(SystemMenu c:childrenMenu){

                if(LongUtil.isNotZreo(c.getParentId())&&
                        c.getParentId().longValue()==p.getId()){
                    Map<String,Object> child = new HashedMap();
                    child.put("id",c.getId());
                    child.put("name",c.getName());
                    child.put("type",SystemRolePermission.system_role_permission_type_menu);
                    child.put("checked",false);
                    //---------是否有三级菜单（功能），如果有就勾选三级菜单（功能）
                  //  if(ListUtil.isNotNull(operateMenu)){
                    logger.info("----菜单"+c.getName()+"---菜单有功能");
                        //三级菜单（功能）
                        List< Map<String,Object>> operates = new ArrayList< Map<String,Object>>();

                            for(SystemMenu o:operateMenu){
                                if(LongUtil.isNotZreo(o.getParentId())&&
                                        o.getParentId().longValue()==c.getId()){
                                    Map<String,Object> operate = new HashedMap();
                                    operate.put("id",o.getId());
                                    operate.put("name","名称："+o.getName()+"，备注："+o.getRemark());
                                    operate.put("type",SystemRolePermission.system_role_permission_type_operate);
                                    operate.put("checked",false);
                                    //匹配功能是否勾选
                                    //匹配子菜单是否勾选
                                    for(SystemRolePermission permission:operatePermissions){
                                        if(LongUtil.isNotZreo(permission.getMenuId())&&
                                                o.getId()==permission.getMenuId().longValue()){
                                            operate.put("checked",true);
                                            break;
                                        }
                                    }
                                    operates.add(operate);
                                  //  break;
                                }
                            }

                           //---------是否有三级菜单（功能），如果没有就勾选二级菜单,如果有就勾选三级菜单（功能）
                            if(ListUtil.isNull(operates)){
                                //匹配子菜单是否勾选
                                for(SystemRolePermission permission:menuPermissions){
                                    if(LongUtil.isNotZreo(permission.getMenuId())&&
                                            c.getId()==permission.getMenuId().longValue()){
                                        logger.info("----菜单"+c.getName()+"---被勾选");
                                        child.put("checked",true);
                                        break;
                                    }
                                }
                            }

                             child.put("children",operates);





                        children.add(child);
                }
            }
            parent.put("children",children);

            results.add(parent);
        }

        return results;
    }
    /**
     * 保存菜单或菜单功能
     * @param roleId
     * @param permissionIds
     * @param types
     */
    public void saveRolePermission(Long roleId,List<Long> permissionIds,List<Integer> types){
        //删除原来的数据
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("roleId",roleId);
        super.doDelete(param);
        //新增本次的
        if(ListUtil.isNotNull(permissionIds)){
            List<SystemRolePermission> rolePermissions = new ArrayList<SystemRolePermission>();
            for(int i=0;i<permissionIds.size();i++){
                Long permissionId=permissionIds.get(i);
                Integer type =types.get(i);
                SystemRolePermission rolePermission = new SystemRolePermission(roleId,permissionId,type);
                rolePermissions.add(rolePermission);
            }
            super.batchSave(rolePermissions);
        }

    }



    /*//分配菜单
    public void saveMenuPermission(Long userId,List<Long> menuIds){



    }*/
    //同步权限（按用户同步）
    //同步权限（所有用户同步）

}
